from django.db import models
from django.contrib.auth import get_user_model
from django.core.exceptions import ObjectDoesNotExist
# Create your models here.
def get_or_init_cart(user):
    try:
        cart=user.cart
    except ObjectDoesNotExist:
        cart=Cart(account=user)
        cart.save()
    return cart

class Location(models.Model):#区
    code=models.IntegerField(primary_key=True)
    name=models.CharField(max_length=64)
    def __str__(self):
        return self.name

class Address(models.Model):
    account=models.ForeignKey(get_user_model(),models.CASCADE)
    location=models.ForeignKey(Location,models.CASCADE)        #邮政编码
    detail=models.CharField(max_length=64)  #详细地址
    def __str__(self):
        return '%s,%s'%(self.location,self.detail)

class Product(models.Model):
    title=models.CharField(max_length=64)
    price=models.FloatField()
    detail=models.TextField(max_length=256)
    def __str__(self):
        return self.title


class CartItem(models.Model):
    product=models.ForeignKey(Product,models.CASCADE)
    counts=models.IntegerField()
    @property
    def total(self):
        return self.product.price*self.counts
    @property
    def title(self):
        return self.product.title
    @property
    def price(self):
        return self.product.price
    def __str__(self):
        return "%s(%s*%s)"%(self.product,self.price,self.counts)

class Cart(models.Model):
    account=models.OneToOneField(get_user_model(),models.CASCADE)
    items=models.ManyToManyField(CartItem)

class Order(models.Model):
    address=models.ForeignKey(Address,models.SET_NULL,null=True)                   #邮寄地址
    account=models.ForeignKey(get_user_model(),models.CASCADE)          #买家
    items=models.ManyToManyField(CartItem)
    price=models.FloatField(default=0)
    confirm=models.BooleanField(default=False)
